import React, { PureComponent } from 'react';
import moment from 'moment';
import { Button, Form, Input, Modal,  Divider,Card,Switch,Badge,message  } from 'antd';
import {Map, Marker, NavigationControl,MapTypeControl,ScaleControl,OverviewMapControl, InfoWindow,TrafficLayer,Road} from 'react-bmap'  ;
import DescriptionList from '../../DescriptionList/index';
import MsgImage from '../MsgImage'
import styles from './index.less';
import MsgModalMap from '../MsgModalMap/index';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Description } = DescriptionList;
//消息来源
const sourceMap = ['来自微信', '来自APP','平台发布','来自webApp'];
//是否审核
const auditMap = ["待审","已审待播","已审已播","导播忽略","主播忽略"];
//消息类型
const messageTypeMap = ['互动','寻人','寻物','车辆求助','寻找失主','其他'];
//语音消息动态图
const radioDetailImageSrcs = [require("../../../../public/audioImage3.png"),require("../../../../public/audioImage4.gif") ];
const bmapCarIcon = require("../../../../public/arrow.png");
let map;
let traffic;
class MsgOtherDetail extends PureComponent {
  state = {
    previewVisible: false,
    replayVisible: false,
    previewImageSrc: '',
    replayMessageValue:"",
    lng:"",
    lat:"",
    drivingDirection:null,
    modalMapVisible:false,
    msgPushStaus:false,
  };
  componentDidMount() {
    var self = this;
    const {selectedRowData} = this.props;
    if(JSON.stringify(selectedRowData) == "{}" ){
      return;
    }
    if(selectedRowData.positionCoor == null || selectedRowData.positionCoor == "" || JSON.stringify(JSON.parse(selectedRowData.positionCoor)) == "{}"){
      this.setState({
        msgPushStaus: selectedRowData.pushStatus == 1 ? true:false,
      });
      return ;
    }
    const lng = JSON.parse(selectedRowData.positionCoor).lng ;
    const lat = JSON.parse(selectedRowData.positionCoor).lat ;
    const drivingDirection = selectedRowData.drivingDirection;
    this.setState({
      lng:lng,
      lat:lat,
      drivingDirection:drivingDirection,
      msgPushStaus: selectedRowData.pushStatus == 1 ? true:false,
    },()=>{
      self.initBmap(lng,lat,drivingDirection);
    });

  }
  componentWillReceiveProps(nextProps){
    var self = this;
    if(nextProps.selectedRowData !== undefined && JSON.stringify(nextProps.selectedRowData) != "{}"){
      var curMsgRadioDetail =  document.getElementById("curRadioMsgImage");
      if(curMsgRadioDetail != undefined ){
        curMsgRadioDetail.src = radioDetailImageSrcs[0];
      }

      const selectedRowData = nextProps.selectedRowData;
      this.setState({
        msgPushStaus: selectedRowData.pushStatus == 1 ? true:false,
      });
      if(selectedRowData.positionCoor == null || selectedRowData.positionCoor == "" || JSON.stringify(JSON.parse(selectedRowData.positionCoor)) == "{}"){
        return;
      }
      const lng = JSON.parse(selectedRowData.positionCoor).lng ;
      const lat = JSON.parse(selectedRowData.positionCoor).lat ;
      const drivingDirection = selectedRowData.drivingDirection;
      this.setState({
        lng:lng,
        lat:lat,
        drivingDirection:drivingDirection,
      },()=>{
        self.initBmap(lng,lat,drivingDirection);
      });
    }
  }
  /**
   * 打开实时路况
   * @param checked
   */
  openShishiRold = (checked) => {
    if(checked){
      traffic = new BMap.TrafficLayer();
      map.addTileLayer(traffic);
    }else{
      map.removeTileLayer(traffic);
    }
  }
  initBmap(lng,lat,drivingDirection){
    const self = this;
    if(lng == ""){
      return ;
    }
    map = new BMap.Map("msgDetailBmapId");
    map.enableScrollWheelZoom(true);
    var point = new BMap.Point(lng,lat);
    map.centerAndZoom(point, 17);


    map.addEventListener("dblclick", function(){
      self.setState({
        modalMapVisible: true,
      });
    })
    map.addControl(new BMap.MapTypeControl());          //添加地图类型控件
    var pt = new BMap.Point(lng, lat);
    var myIcon = new BMap.Icon(bmapCarIcon,new BMap.Size(32,32));
    var marker2 = new BMap.Marker(pt,{icon:myIcon});  // 创建标注
    if(drivingDirection != null){
      marker2.setRotation(drivingDirection);
    }
    traffic = new BMap.TrafficLayer();
    map.addTileLayer(traffic);
    map.addOverlay(marker2);              // 将标注添加到地图中
  }
  /**
   * 打开和关闭图片显示
   */
  handleImageModalShow = (imgSrc) => {
    this.setState({
      previewImageSrc: imgSrc,
      previewVisible: true,
    });
  }
  handleImageModalCancel = () => {
    this.setState({ previewVisible: false })
  }

  handleCancelBMapModal = () => {
    this.setState({
      modalMapVisible: false,
    });
  }

  /**
   * 打开消息回复窗口
   * @param flag
   */
  handleShowReplayModal = (flag) => {
    this.setState({
      replayVisible: !!flag,
    });
  }

  handleReplayMessage = (helpId,userId) => {
    const replayMessageValue = this.state.replayMessageValue;
    this.props.handleReplayMessage(helpId,userId,replayMessageValue);
    this.setState({
      replayVisible: false,
      replayMessageValue:""
    });
  }

  handleAddReplayMessageValue = (e) => {
      this.setState({
        replayMessageValue: e.target.value,
      });
  }

  /**
   * 一键推送 求助消息
   * @param helpId
   */
  handlePushMsgHelp = (helpId,selectedRowIndex) => {
    this.props.handlePushMsgHelp(helpId,selectedRowIndex);
    this.setState({
      msgPushStaus: true,
    });
  }
  /**
   * 语音播放
   * */
  handleCurMsgMusicPlay= () => {
    var radioValue = this.props.radioValue;
    var audioCurMsg = this.refs.audioCurMsgMusicPlay;
    var curMsgRadioDetail =  document.getElementById("curRadioMsgImage");

    audioCurMsg.onended = function () {
      curMsgRadioDetail.src = radioDetailImageSrcs[0];
    }
    audioCurMsg.playbackRate = radioValue;
    if(audioCurMsg.paused){
      curMsgRadioDetail.src = radioDetailImageSrcs[1];
      audioCurMsg.play();
    }else{
      curMsgRadioDetail.src = radioDetailImageSrcs[0];
      audioCurMsg.pause();
    }
  }
  render() {
    const {previewVisible, previewImageSrc, replayVisible, replayMessageValue,lng,lat,drivingDirection,modalMapVisible,msgPushStaus} = this.state;
    const {selectedRowData,selectedRowIndex} = this.props;
    let addrStr = selectedRowData.addrStr&&selectedRowData.addrStr.startsWith("{")?JSON.parse(selectedRowData.addrStr):null;
    let addrName = addrStr?addrStr.name:selectedRowData.addrStr;
    let addrFullName = addrStr?addrStr.fname:null;

    const showModalMap = (
      <Modal
        visible={modalMapVisible}
        maskClosable={true}
        footer={null}
        onCancel={this.handleCancelBMapModal}
        width={document.body.clientWidth*0.8}
      >
        <MsgModalMap
          lng={lng}
          lat={lat}
          drivingDirection={drivingDirection}
        >
        </MsgModalMap>
      </Modal>
    )
    return (
      <div style={{height: "auto"}}>
        <Card bordered={false}>
          <DescriptionList style={{marginBottom: 16}} col={2}>
            <Description term="时间">{moment(selectedRowData.msgTime).format('YYYY-MM-DD HH:mm:ss')}</Description>
            <Description term="审核">
              <span>{auditMap[selectedRowData.status]}</span>
              {selectedRowData.messageFrom === 3 ? null:
                <Button type="primary" style={{marginLeft: 40}} size="small"
                        onClick={() => this.handleShowReplayModal(true)}>回复消息
                </Button>
              }
            </Description>
            <Description term="类型">{messageTypeMap[selectedRowData.msgType]}</Description>
            <Description term="来源">{sourceMap[selectedRowData.messageFrom]}</Description>
          </DescriptionList>
          <Divider style={{marginBottom: 16}}/>
          <DescriptionList style={{marginBottom:8}} col={2}>
            <Description term="求助人">{selectedRowData.seekerName}</Description>
            <Description term="联系人">{selectedRowData.contacts}</Description>
          </DescriptionList>

          <DescriptionList style={{marginBottom: 8}} col={2}>
            <Description term="联系电话">{selectedRowData.contactsTell}</Description>
          </DescriptionList>
          <DescriptionList style={{marginBottom: 8}} col={1}>
            {
              selectedRowData.seekVoice == "" ?  <Description term="求助描述">{selectedRowData.seekDes}</Description> :
                <Description term="求助语音">
                  <div style={{marginLeft:2}}>
                    <div onClick={() => this.handleCurMsgMusicPlay()} style={{float:"left", height:26,width:135,backgroundImage:"url("+require("../../../../public/audioImage.png")+")",cursor:"pointer" }}>
                      <img src={radioDetailImageSrcs[0]} id="curRadioMsgImage" style={{marginLeft:10, height:26,width:26}}/>
                    </div>
                    <div style={{float:"left",marginTop:3}}>{selectedRowData.radioLen}"</div>
                  </div>
                </Description>
            }
          </DescriptionList>
          <DescriptionList style={{marginBottom: 8}} col={1}>
            <Description term="求助位置">{addrName}</Description>
          </DescriptionList>
          <DescriptionList  col={1}>
            <Description term="详细位置">{addrFullName}</Description>
          </DescriptionList>
          {
            (selectedRowData.positionCoor == null || selectedRowData.positionCoor == "") ? (
              <div>
                <DescriptionList style={{marginTop:20,marginBottom: 5,paddingLeft:110}} col={2}>
                  <Description term=""></Description>
                  <Description term="实时路况">
                    <div>
                      <Switch  onChange={this.openShishiRold} defaultChecked />
                    </div>
                    <div>
                      <Badge status="error" text="拥堵"/>
                      <Badge status="warning" text="缓行"/>
                      <Badge status="success" text="通常"/>
                    </div>
                  </Description>
                </DescriptionList>
                <Card style={{ backgroundColor:"#000",background:  "rgba(0, 0, 0, 0.5)"}}>
                  <Map center={{ lng: 87.490354 ,lat: 43.853289}}
                       zoom="18"
                  >
                    <div style={{width: "100%", height: "100%",position: 'absolute', left: '0px', top: '0px',  backgroundColor:"#000",background: "rgba(0, 0, 0, 0.5)",textAlign:"center"}}>
                      <div style={{color:"#FFFFFF",fontSize:32,position: "absolute",left:"30%", top: "30%"}}><span >暂无位置和方向信息</span></div>
                    </div>
                  </Map>
                </Card>
              </div>
            ) : (
              <div>
                <DescriptionList style={{marginTop:20,marginBottom: 5,paddingLeft:110}} col={2}>
                  <Description term=""></Description>
                  <Description term="实时路况">
                    <div>
                      <Switch  onChange={this.openShishiRold} defaultChecked />
                    </div>
                    <div>
                      <Badge status="error" text="拥堵"/>
                      <Badge status="warning" text="缓行"/>
                      <Badge status="success" text="通常"/>
                    </div>
                  </Description>
                </DescriptionList>
                <Card >
                  <div id="msgDetailBmapId" style={{width:'100%',height:400}}></div>
                </Card>
              </div>
            )
          }

        </Card>
        {
          selectedRowData.photoInfo == "" ? "": <Card bordered={false}>
            <DescriptionList style={{marginBottom: 16}} col={1}>
              <Description term="求助照片"></Description>
            </DescriptionList>
            <MsgImage
              imageSrc={selectedRowData.photoInfo}
              handleImagePlay={(imgSrc) => this.handleImageModalShow(imgSrc)}
            />
            <Modal visible={previewVisible} footer={null} onCancel={this.handleImageModalCancel}>
              <img alt="example" style={{width: '100%'}} src={previewImageSrc}/>
            </Modal>
          </Card>
        }
        <Card bordered={false}>
          <div style={{float: 'right'}}>
            {msgPushStaus == true ?
              <Button type="primary" disabled  >一键推送</Button>
              :<Button type="primary" onClick={() => this.handlePushMsgHelp(selectedRowData.helpId,selectedRowIndex)} >一键推送</Button>}

          </div>
          <Modal
            title="消息回复"
            visible={replayVisible}
            onOk={() => this.handleReplayMessage(selectedRowData.helpId,selectedRowData.userId)}
            onCancel={() => this.handleShowReplayModal(false)}
            okText="发送"
          >
            <FormItem
              labelCol={{span: 5}}
              wrapperCol={{span: 15}}
              label="描述"
            >
              <TextArea rows={5} placeholder="请输入" onChange={this.handleAddReplayMessageValue}
                        value={replayMessageValue}/>
            </FormItem>
          </Modal>
        </Card>
        <Card bordered={false}>
          <DescriptionList col={1}>
            <Description term="提示:"> 推送成功后，求助信息将会显示到APP中寻人寻物界面，可提示热心听众在APP中查看详情。</Description>
          </DescriptionList>
        </Card>
        {/* 音乐播放组件*/}
        <audio ref="audioCurMsgMusicPlay"
               style={{display:"none"}}
               src={selectedRowData.seekVoice}
               preload={"auto"}
        > 您当前的浏览器不支持该播放控件
        </audio>
        {modalMapVisible?showModalMap:null}
      </div>
    );
  }
}

export default MsgOtherDetail ;
